<?php 

class Application_Model_Post
{
	protected $_dbTable;
	
	public function __construct() {
		$this->_dbTable = new Application_Model_DbTable_Post();
	}
	
	public function addPost ($data) 
	{
		$this->_dbTable->insert($data);
	}
	
	public function updatePost($data, $id) 
	{
		$this->_dbTable->update($data, "id={$id}");
	}
	
	public function fetchAllOrderDesc($param = array()) 
	{
		$select = $this->_dbTable->select()
        ->order('id desc');	
		if ($param) foreach ($param as $p) {
			$select->where($p);
		}
		
		return $this->_dbTable->fetchAll($select)->toArray();
	}
	
	public function getById($id)
	{
		$rows = $this->_dbTable->fetchAll(
			$this->_dbTable->select()
				->where('id = ?', $id)
				->limit(1, 0)
			);
		return $rows[0];
	}
	
	public function getByAlias($id)
	{
		$rows = $this->_dbTable->fetchAll(
			$this->_dbTable->select()
				->where('alias = ?', $id)
				->limit(1, 0)
			);
		return $rows[0];
	}
	
	public function getLatestPost($num_post = 10) 
	{
		$rows = $this->_dbTable->fetchAll(
			$this->_dbTable->select()
				->order('id desc')
				->limit($num_post, 0)
			);
		return $rows;
	}
	
	public function getsTop($field, $param=array(), $limit = 10, $offset = 0) {
		$select = $this->_dbTable->select()
				->order($field.' desc')
				->limit($limit, $offset);
		if (!empty($param)) foreach ($param as $p) {
			$select->where($p);
		}
		$rows = $this->_dbTable->fetchAll(
			$select
			);
		return $rows;
	}
	
	public function getByCategory($cate_id,$param=array(), $limit = 10, $offset = 0, $order = 'desc') 
	{
		$select = $this->_dbTable->select()
				->where('category_id=?', $cate_id)
				->order('id '.$order);
		if ($param) foreach ($param as $p) {
			$select->where($p);
		}
		if ($limit != 0)
			$select->limit($limit, $offset);
		$rows = $this->_dbTable->fetchAll($select);
		return $rows;
	}
	
}